package com.sita.friend.ui.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyTrafficStyle;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.enums.PathPlanningStrategy;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.amap.api.services.core.LatLonPoint;
import com.autonavi.tbt.TrafficFacilityInfo;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.sita.bike.R;
import com.sita.bike.model.EaseUser2;
import com.sita.bike.persistence.GroupMember;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.FriendActionsRequest;
import com.sita.bike.rest.model.Location;
import com.sita.bike.rest.model.RestResponse;
import com.sita.bike.rest.model.SenderInfo;
import com.sita.bike.rest.model.SenderPoiInfo;
import com.sita.bike.rest.model.ShareLocationOneTime;
import com.sita.bike.rest.model.ShareLocationPOI;
import com.sita.bike.rest.model.ShareLocationRealTime;
import com.sita.bike.rest.model.ShareLocationRealTimeStop;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.BitmapUtils;
import com.sita.bike.utils.PersistUtils;
import com.sita.friend.Constant;
import com.sita.friend.FriendHelper;
import com.sita.friend.event.CalculateDriveRouteEvent;
import com.sita.friend.event.ConversationMessageHasReadEvent;
import com.sita.friend.event.ReceviceShareLocOneEvent;
import com.sita.friend.event.ReceviceShareLocRealTimeEvent;
import com.sita.friend.event.ReceviceStopShareLocEvent;
import com.sita.friend.event.SendDestinationEvent;
import com.sita.friend.event.UserAvatarLoadEvent;
import com.sita.friend.ui.adapter.GroupShareLocMemberAdapter;
import com.sita.friend.ui.widget.EaseChatMessageList;
import com.sita.friend.ui.widget.HorizontalListView;
import com.sita.tboard.ActivityBase;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedString;


public class ChatActivity extends ActivityBase implements AMapLocationListener,
        AMap.OnMarkerClickListener,
        AMap.OnInfoWindowClickListener,
        AMap.OnMarkerDragListener,
        AMap.OnMapLoadedListener,
        View.OnClickListener,
        AMap.InfoWindowAdapter,
        AMap.OnMapLongClickListener,
        AMap.OnMapClickListener,
        EMEventListener,
        AMapNaviListener {
    private static final LatLng TIANJIN = new LatLng(39.08662, 117.203887);
    private static final CameraPosition CAMERA_POSITION_TIANJIN = new CameraPosition.Builder()
            .target(TIANJIN).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(30).build();
    private static final int REQUEST_CODE_SELECT_VIDEO = 11;
    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;
    private static final int REQUEST_CODE_SELECT_DISTINATION = 1;
    public static ChatActivity activityInstance;
    protected AMap aMap;
    protected TextureMapView mapView;
    protected int chatType;
    protected EMConversation conversation;
    String toChatUsername, toChatLocGroupId;
    private RelativeLayout sharringLocationLayout, joinSharingWindow;
    private int listenerId;
    private Marker myMarker, myPoiMarker, friendMarker, friendPoiMarker;
    private MarkerOptions myMarkerOption, myPoiMarkerOption, friendMarkerOption, friendPoiMarkerOption;
    private LatLng latlng = new LatLng(36.061, 103.834);
    private RelativeLayout message_list_handle_down, message_list_handle_up;
    private ImageView img_mysharing_shutdown, friendSharingShutdown;
    private RelativeLayout layout_message_list, chat_main_layout, layout_friend_chat_map_view;
    private TextureMapView friend_chat_map_view;
    private EaseChatMessageList message_list;
    private ListView listView;
    private Button mSendMessage, joinSharingCancel, joinSharingSure;
    private EditText mSendMessageContent;
    private Bitmap redpin_zoom, overlayEnd;
    private SwipeRefreshLayout swipeRefreshLayout;
    private boolean isloading;
    private boolean haveMoreData = true;
    private int pagesize = 20;
    private boolean isMessageListInited;
    private boolean realShareIsStop = true;
    private boolean joinRealShareIsCanael = false;
    private ShareRelTimeLocationThread shareRelTimeLocationThread;
    private AMapLocationClient aMapLocationClient;
    private boolean isSita = false;
    private ImageView imgGroupDetail = null;
    private TextView chat_title, friendSharingHint;
    private HorizontalListView sharingMembers;
    private ArrayList<String> listItems = new ArrayList<>();//存放群组中共享位置成员的id
    private GroupShareLocMemberAdapter groupShareAdapter;
    private RelativeLayout joinBtnLayout, layout_chat_share_loc;
    private ImageView btn_chat_send_loc, btn_share_one_loc, btn_share_rel_loc, btn_share_dist;
    // 起点终点坐标
    private NaviLatLng mNaviStart = new NaviLatLng(39.989614, 116.481763);
    private NaviLatLng mNaviEnd = new NaviLatLng(39.983456, 116.3154950);
    // 起点终点列表
    private ArrayList<NaviLatLng> mStartPoints = new ArrayList<>();
    private ArrayList<NaviLatLng> mEndPoints = new ArrayList<>();
    // 规划线路
    private RouteOverLay mRouteOverLay;
    private AMapNavi aMapNavi;
    private Map<String, Marker> mapIdMarker = new HashMap<>();//存放分享位置的好友的id-marker
    private boolean isShareLocationBtnShown = false;
    private ImageView chat_Back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //聊天人或群id,群组时为环信id
        toChatUsername = getIntent().getExtras().getString(Constant.CHAT_PARAMS_USER_ID);
        //单聊还是群聊
        chatType = getIntent().getExtras().getInt(Constant.CHAT_PARAMS_TYPE);

        setContentView(R.layout.activity_chat);

        EventBus.getDefault().register(this);
        // toolbar
        imgGroupDetail = (ImageView) findViewById(R.id.img_chat_group_detail);
        if (chatType == Constant.CHATTYPE_GROUP) {
            //判断本地是不是存了群信息，否，请求保存群信息
            boolean b = PersistUtils.containEaseGroupId(toChatUsername);
            if (!PersistUtils.containEaseGroupId(toChatUsername)) {
                AccountUtils.saveGroupMembers(toChatUsername, true);
            }
            imgGroupDetail.setVisibility(View.VISIBLE);
            imgGroupDetail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toGroupDetails();
                }
            });
        } else {
            imgGroupDetail.setVisibility(View.GONE);
        }

        // chat title view
        chat_title = (TextView) findViewById(R.id.chat_title);
        String niceName = null;
        if (chatType == Constant.CHATTYPE_SINGLE) {
            EaseUser2 easeUser2 = FriendHelper.getInstance().getContactUser(toChatUsername);
            if (easeUser2.getNick() != null) {
                niceName = easeUser2.getNick();
            } else if (easeUser2.getUsername() != null) {
                niceName = easeUser2.getUsername();
            }
        } else if (chatType == Constant.CHATTYPE_GROUP) {
            EMGroup group = EMGroupManager.getInstance().getGroup(toChatUsername);
            niceName = group.getNick();
        }
        if (niceName.length() > 10) {
            String showName = niceName.substring(0, 10) + "...";
            chat_title.setText(showName);
        } else {
            chat_title.setText(niceName);
        }

        // amap view
        mapView = (TextureMapView) findViewById(R.id.friend_chat_map_view);
        mapView.onCreate(savedInstanceState);
        initMap();
        aMapNavi = AMapNavi.getInstance(this);
        aMapNavi.addAMapNaviListener(this);
        aMapNavi.setEmulatorNaviSpeed(150);
        mRouteOverLay = new RouteOverLay(aMap, null);
        img_mysharing_shutdown = (ImageView) findViewById(R.id.img_mysharing_shutdown);
        message_list_handle_down = (RelativeLayout) findViewById(R.id.message_list_handle_down);
        message_list_handle_up = (RelativeLayout) findViewById(R.id.message_list_handle_up);
        chat_Back = (ImageView) findViewById(R.id.road_trust_img_back);
        // message list
        layout_message_list = (RelativeLayout) findViewById(R.id.layout_message_list);
        message_list = (EaseChatMessageList) findViewById(R.id.message_list);
        if (chatType != Constant.CHATTYPE_SINGLE)
            message_list.setShowUserNick(true);
        listView = message_list.getListView();

        swipeRefreshLayout = message_list.getSwipeRefreshLayout();
        swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_light,
                R.color.holo_orange_light, R.color.holo_red_light);

        activityInstance = this;

        //message send
        mSendMessageContent = (EditText) findViewById(R.id.chat_send_message_content);
        mSendMessageContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    String msg = mSendMessageContent.getText().toString();
                    if (!TextUtils.isEmpty(msg)) {
                        sendTextMessage(msg);
                        mSendMessageContent.setText("");
                    }
                    return true;
                }
                return false;
            }
        });

        setUpChatView();

        aMapLocationClient = GlobalContext.getLocationClient();
//        //可以直接new EaseChatFratFragment使用
//        chatFragment = new ChatFragment();
//        //传入参数
//        chatFragment.setArguments(getIntent().getExtras());
//        getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commit();

        chat_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (realShareIsStop == false) {
                    dialog();
                } else {
                    finish();
                }
            }
        });
        img_mysharing_shutdown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doStopRealTimeLocation();
                sharringLocationLayout.setVisibility(View.GONE);
                String msg = "结束实时共享";
                if (!TextUtils.isEmpty(msg))
                    sendTextMessage(msg);

            }
        });
        //正在位置共享
        sharringLocationLayout = (RelativeLayout) findViewById(R.id.layout_mysharring_location);
        joinBtnLayout = (RelativeLayout) findViewById(R.id.layout_join_btn);
        //是否加入位置共享
        joinSharingWindow = (RelativeLayout) findViewById(R.id.layout_friend_sharring_location);
        joinSharingCancel = (Button) findViewById(R.id.join_friend_sharring_cancel);
        joinSharingSure = (Button) findViewById(R.id.join_friend_sharring_sure);
        friendSharingShutdown = (ImageView) findViewById(R.id.img_friend_sharing_shutdown);
        friendSharingHint = (TextView) findViewById(R.id.text_friend_sharing);
        sharingMembers = (HorizontalListView) findViewById(R.id.horizontal_list_sharing_member);
        friendSharingShutdown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // joinRealShareIsCanael = true;
                doStopRealTimeLocation();
                //从分享list中删除自己，判断分享列表是不是等于零个
                if (listItems.size() == 0) {
                    joinSharingWindow.setVisibility(View.GONE);
                }
                String msg = "结束实时共享";
                if (!TextUtils.isEmpty(msg))
                    sendTextMessage(msg);
            }
        });
        joinSharingCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                joinSharingWindow.setVisibility(View.GONE);
//                joinRealShareIsCanael = true;
            }
        });
        joinSharingSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (chatType == Constant.CHATTYPE_SINGLE) {
                    joinSharingWindow.setVisibility(View.GONE);
                    sharringLocationLayout.setVisibility(View.VISIBLE);
                } else if (chatType == Constant.CHATTYPE_GROUP) {
                    friendSharingHint.setVisibility(View.GONE);
                    sharingMembers.setVisibility(View.VISIBLE);
                    joinBtnLayout.setVisibility(View.GONE);
                }
                doShareRealTimeLocation();
            }
        });
        sharingMembers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //拿到当前选中的id
                String itemId = listItems.get(position);
                //通过id找到marker
                Marker marker = mapIdMarker.get(itemId);
                //若为空则是自己
                if (marker == null) {
                    marker = myMarker;
                }
                LatLng markerLatLng = marker.getPosition();
                CameraPosition cameraPosition = new CameraPosition.Builder().target(markerLatLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
                CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
                aMap.moveCamera(update);
            }
        });


        //发送位置
        btn_chat_send_loc = (ImageView) findViewById(R.id.btn_chat_send_loc);
        layout_chat_share_loc = (RelativeLayout) findViewById(R.id.layout_chat_share_loc);
        btn_share_one_loc = (ImageView) findViewById(R.id.btn_share_one_loc);
        btn_share_rel_loc = (ImageView) findViewById(R.id.btn_share_rel_loc);
        btn_share_dist = (ImageView) findViewById(R.id.btn_share_dist);
        btn_chat_send_loc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShareLocationBtnShown) {
                    layout_chat_share_loc.setVisibility(View.GONE);
                    isShareLocationBtnShown = false;
                } else {
                    layout_chat_share_loc.setVisibility(View.VISIBLE);
                    isShareLocationBtnShown = true;
                }

            }
        });
        btn_share_one_loc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doShareOneTimeLocation();
                String msg = "发送了当前位置";
                if (!TextUtils.isEmpty(msg))
                    sendTextMessage(msg);
                layout_chat_share_loc.setVisibility(View.GONE);
            }
        });
        btn_share_rel_loc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sharringLocationLayout.setVisibility(View.VISIBLE);
                doShareRealTimeLocation();
                String msg = "正在实时共享";
                if (!TextUtils.isEmpty(msg))
                    sendTextMessage(msg);
                layout_chat_share_loc.setVisibility(View.GONE);
            }
        });
        btn_share_dist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getApplicationContext(),RoutePlanningActivity.class);
//                startActivityForResult(intent,REQUEST_CODE_SELECT_DISTINATION);
//                layout_chat_share_loc.setVisibility(View.GONE);
                Intent intent = new Intent(getApplicationContext(), PoiDestinationSearchActivity.class);
                startActivity(intent);
                layout_chat_share_loc.setVisibility(View.GONE);
            }
        });

        //下拉地图
        message_list_handle_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout_message_list.setVisibility(View.GONE);
                message_list_handle_up.setVisibility(View.VISIBLE);
            }
        });
        message_list_handle_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout_message_list.setVisibility(View.VISIBLE);
                message_list_handle_up.setVisibility(View.GONE);
            }
        });

    }

    @Override
    public void onMapClick(LatLng latLng) {
        if ((myMarker != null) && (myMarker.isInfoWindowShown())) {
            myMarker.hideInfoWindow();
        } else if ((myPoiMarker != null) && (myPoiMarker.isInfoWindowShown())) {
            myPoiMarker.hideInfoWindow();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        aMapLocationClient.setLocationListener(this);
        if (!aMapLocationClient.isStarted()) {
            aMapLocationClient.startLocation();
        }
        if (mapView != null) {
            mapView.onResume();
        }

        if (isMessageListInited)
            message_list.refresh();
        // register the event listener when enter the foreground
        EMChatManager.getInstance().registerEventListener(
                this,
                new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage,
                        EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventDeliveryAck,
                        EMNotifierEvent.Event.EventReadAck});
        EMChat.getInstance().setAppInited();
        mStartPoints.add(mNaviStart);
        mEndPoints.add(mNaviEnd);

    }

    @Override
    public void onPause() {
        if (mapView != null) {
            mapView.onPause();
        }
        GlobalContext.getLocationClient().unRegisterLocationListener(this);
        super.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    public void onEventMainThread(ReceviceShareLocOneEvent event) {
        EMMessage message = event.getEMMessage();
        // 如果是当前会话的消息，刷新聊天页面
        Location location = null;
        SenderInfo senderInfo = null;
        try {
            JSONObject attr = message.getJSONObjectAttribute(Constant.CMD_LOC_ACTION_RECEVICE_ONE);
            if (attr.has("location")) {
                location = RestClient.getGson().fromJson(attr.getJSONObject("location").toString(), Location.class);
            }
            if (attr.has("senderInfo")) {
                senderInfo = RestClient.getGson().fromJson(attr.getJSONObject("senderInfo").toString(), SenderInfo.class);
            }
        } catch (EaseMobException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LatLng latLng = new LatLng(Double.parseDouble(location.latitude), Double.parseDouble(location.longitude));
        String mImid = senderInfo.mImid;
        String mTargetId = senderInfo.mTargetid;

        if (chatType == Constant.CHATTYPE_SINGLE) {
            if (mImid.equals(toChatUsername)) {
                EaseUser2 easeUser2 = FriendHelper.getInstance().getContactUser(mImid);
                Bitmap friendAvatar = AccountUtils.getUserAvatar(easeUser2.getAvatar());
                addFriendMarkerToMap(latLng, mImid, friendAvatar);
            }
        } else if (chatType == Constant.CHATTYPE_GROUP) {
            String mGroupId = PersistUtils.getEaseGroupId(mTargetId);
            if (mGroupId.equals(toChatUsername)) {
                //获取发送者的头像,判断是不是好友关系
                EaseUser2 easeUser2 = FriendHelper.getInstance().getContactUser(mImid);
                if (easeUser2 != null) {
                    Bitmap friendAvatar = AccountUtils.getUserAvatar(easeUser2.getAvatar());
                    addFriendMarkerToMap(latLng, mImid, friendAvatar);
                } else {
                    //从本地存储的member中查找用户
                    GroupMember groupMember = PersistUtils.getGroupMember(mImid);
                    Bitmap memberAvatar = AccountUtils.getMemberAvatar(groupMember.getAvatarUrl());
                    addFriendMarkerToMap(latLng, mImid, memberAvatar);
                }
            }
        }
    }

    public void onEventMainThread(ReceviceShareLocRealTimeEvent event) {
        //若此时自己未实时共享位置，弹出是否加入对话框
//            if(realShareIsStop&&!joinRealShareIsCanael){
        if (realShareIsStop) {
            joinSharingWindow.setVisibility(View.VISIBLE);
            if (chatType == Constant.CHATTYPE_GROUP) {
                friendSharingHint.setVisibility(View.GONE);
                sharingMembers.setVisibility(View.VISIBLE);
            }
        }

        EMMessage message = event.getEMMessage();
        // 如果是当前会话的消息，刷新聊天页面
        Location location = null;
        SenderInfo senderInfo = null;
        try {
            JSONObject attr = message.getJSONObjectAttribute(Constant.CMD_LOC_ACTION_RECEVICE_REAL);
            if (attr.has("location")) {
                location = RestClient.getGson().fromJson(attr.getJSONObject("location").toString(), Location.class);
            }
            if (attr.has("senderInfo")) {
                senderInfo = RestClient.getGson().fromJson(attr.getJSONObject("senderInfo").toString(), SenderInfo.class);
            }
        } catch (EaseMobException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LatLng latLng = new LatLng(Double.parseDouble(location.latitude), Double.parseDouble(location.longitude));
        String mImid = senderInfo.mImid;
        String mTargetId = senderInfo.mTargetid;
        if (!mImid.equals(AccountUtils.getAccountID())) {
            if (chatType == Constant.CHATTYPE_SINGLE) {
                if (mImid.equals(toChatUsername)) {
                    EaseUser2 easeUser2 = FriendHelper.getInstance().getContactUser(mImid);
                    Bitmap friendAvatar = AccountUtils.getUserAvatar(easeUser2.getAvatar());
                    addFriendMarkerToMap(latLng, mImid, friendAvatar);
                }
            } else if (chatType == Constant.CHATTYPE_GROUP) {
                String mGroupId = PersistUtils.getEaseGroupId(mTargetId);
                if (mGroupId.equals(toChatUsername)) {
                    if (!listItems.contains(mImid)) {
                        listItems.add(mImid);
                        if (groupShareAdapter == null) {
                            groupShareAdapter = new GroupShareLocMemberAdapter(this, listItems);
                            sharingMembers.setAdapter(groupShareAdapter);
                        }
                        groupShareAdapter.refresh(listItems);
                        setHorListWidth();
                    }
                    //获取发送者的头像,判断是不是好友关系
                    EaseUser2 easeUser2 = FriendHelper.getInstance().getContactUser(mImid);
                    if (easeUser2 != null) {
                        Bitmap friendAvatar = AccountUtils.getUserAvatar(easeUser2.getAvatar());
                        addFriendMarkerToMap(latLng, mImid, friendAvatar);
                    } else {
                        //从本地存储的member中查找用户
                        GroupMember groupMember = PersistUtils.getGroupMember(mImid);
                        Bitmap memberAvatar = AccountUtils.getMemberAvatar(groupMember.getAvatarUrl());
                        addFriendMarkerToMap(latLng, mImid, memberAvatar);
                    }
                }
            }
        }
    }

    public void onEventMainThread(ReceviceStopShareLocEvent event) {
        EMMessage message = event.getEMMessage();
        // 如果是当前会话的消息，刷新聊天页面
        SenderInfo senderInfo = null;
        try {
            JSONObject attr = message.getJSONObjectAttribute(Constant.CMD_LOC_ACTION_RECEVICE_REAL);
            if (attr.has("senderInfo")) {
                senderInfo = RestClient.getGson().fromJson(attr.getJSONObject("senderInfo").toString(), SenderInfo.class);
            }
        } catch (EaseMobException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String mImid = senderInfo.mImid;
        String mTargetId = senderInfo.mTargetid;
        if (mapIdMarker.containsKey(mImid)) {
            Marker friendMarker = mapIdMarker.get(mImid);
            friendMarker.remove();
        }
        listItems.remove(mImid);
        mapIdMarker.remove(mImid);
        if (listItems.size() == 0) {
            joinSharingWindow.setVisibility(View.GONE);
        } else {
            groupShareAdapter.refresh(listItems);
        }
        setHorListWidth();
    }

    public void onEventMainThread(UserAvatarLoadEvent event) {
        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        String myAvatarUrl = AccountUtils.getAvatar();
        Bitmap myAvatar = AccountUtils.getUserAvatar(myAvatarUrl);
        Bitmap bitmap = BitmapUtils.composeBitmap(R.drawable.location_green, myAvatar, 100, 75, 0.9f);
        BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(bitmap);
        addMyMarkersToMap(latLng);
    }

    public void onEventMainThread(CalculateDriveRouteEvent event) {
        EMMessage emMessage = event.getEMMessage();
        calculateDriveRoute(emMessage);
    }

    public void onEventMainThread(SendDestinationEvent event) {
        LatLonPoint latLonPoint = event.getLatLonPoint();
        String mapShotPath = event.getMapShotPath();
        String locationLab = event.getLocationLab();
        EMMessage mess = EMMessage.createImageSendMessage(mapShotPath, false, toChatUsername);
        mess.setAttribute("poiLatitude", String.valueOf(latLonPoint.getLatitude()));
        mess.setAttribute("poiLongitude", String.valueOf(latLonPoint.getLongitude()));
        mess.setAttribute("locationlab", locationLab);
        sendMessage(mess);
    }

    @Override
    public void onDestroy() {
        if (mapView != null) {
            mapView.onDestroy();
        }
        aMapNavi.destroy();
        GlobalContext.getLocationClient().setLocationListener(this);
        activityInstance = null;
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 在地图上添加marker
     */
    private void addMyMarkersToMap(LatLng latlng) {
        //文字显示标注，可以设置显示内容，位置，字体大小颜色，背景色旋转角度
        final String myAvatarUrl = AccountUtils.getAvatar();
        Bitmap myAvatar = AccountUtils.getUserAvatar(myAvatarUrl);
        if (myAvatar == null) {
            loadUserAvatar(myAvatarUrl);
        }
        Bitmap bitmap = BitmapUtils.composeBitmap(R.drawable.location_green, myAvatar, 100, 75, 0.9f);
        BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(bitmap);
        if (myMarkerOption == null) {
            myMarkerOption = new MarkerOptions();
            myMarkerOption.position(latlng);
            myMarkerOption.title("本人").snippet("位置");
            myMarkerOption.icon(icon);
            // 将Marker设置为贴地显示，可以双指下拉看效果
            myMarkerOption.setFlat(true);
            myMarker = aMap.addMarker(myMarkerOption);
        } else {
            myMarker.setIcon(icon);
            myMarker.setPosition(latlng);
        }
    }

    private void addFriendMarkerToMap(LatLng latlng, String accountId, Bitmap friendAvatar) {
        //判断ID对应的marker有没有
        if (!mapIdMarker.containsKey(accountId)) {
            //如果不存在
            MarkerOptions friendMarkerOption = new MarkerOptions();
            friendMarkerOption.position(latlng);
            friendMarkerOption.title("朋友位置").snippet("天津市");
            friendMarkerOption.draggable(true);
            Bitmap bitmap = BitmapUtils.composeBitmap(R.drawable.location_green, friendAvatar, 100, 75, 0.9f);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(bitmap);
            friendMarkerOption.icon(icon);
            // 将Marker设置为贴地显示，可以双指下拉看效果
            friendMarkerOption.setFlat(true);
            Marker friendMarker = aMap.addMarker(friendMarkerOption);
            mapIdMarker.put(accountId, friendMarker);
        } else {
            Marker friendMarker = mapIdMarker.get(accountId);
            if (!friendMarker.isVisible()) {
                friendMarker = aMap.addMarker(friendMarkerOption);
            }
            friendMarker.setPosition(latlng);
        }
    }

    private void loadUserAvatar(String mAvatarUrl) {
        new AsyncTask<String, Void, Void>() {
            @Override
            protected Void doInBackground(String... params) {
                String avatarUrl = params[0];
                try {
                    Bitmap bitmap = Picasso.with(GlobalContext.getGlobalContext()).load(avatarUrl)
                            .get();
                    AccountUtils.addUserAvatar(avatarUrl, bitmap);
                    EventBus.getDefault().post(new UserAvatarLoadEvent("useravatarload complete"));
                } catch (IOException e) {
                }
                return null;
            }
        }.execute(mAvatarUrl);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // 点击notification bar进入聊天页面，保证只有一个聊天页面
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }
    }

    @Override
    public void onBackPressed() {

    }

    public String getToChatUsername() {
        return toChatUsername;
    }

    protected void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setMapUi();
            setUpMap();
        }
        Bitmap redpin = BitmapFactory.decodeResource(getResources(), R.drawable.redpin);
        redpin_zoom = BitmapUtils.zoomBitmap(redpin, 96, 136);
//        Bitmap locationEnd = BitmapFactory.decodeResource(getResources(), R.drawable.location_end);
        setTraffic();
        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        addMyMarkersToMap(latLng);// 往地图上添加marker
        CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(update);
    }

    private void setMapUi() {
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(true);
        mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(CAMERA_POSITION_TIANJIN);
        aMap.moveCamera(update);
    }

    private void setUpMap() {
        aMap.setOnMarkerDragListener(this);// 设置marker可拖拽事件监听器
        aMap.setOnMapLoadedListener(this);// 设置amap加载成功事件监听器
        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        aMap.setOnMapLongClickListener(this);
        aMap.setOnMapClickListener(this);
    }

    private void setTraffic() {
        MyTrafficStyle myTrafficStyle = new MyTrafficStyle();
        myTrafficStyle.setSeriousCongestedColor(0xff92000a);
        myTrafficStyle.setCongestedColor(0xffea0312);
        myTrafficStyle.setSlowColor(0xffff7508);
        myTrafficStyle.setSmoothColor(0xff00a209);
        aMap.setTrafficEnabled(false);
    }

    /*
 * get own location
 */
    @Override
    public void onLocationChanged(AMapLocation location) {
        if (location != null) {
            Double longitude = location.getLongitude();
            Double latitude = location.getLatitude();
            if (isValidGps(longitude, latitude)) {
                LatLng latLng = new LatLng(latitude, longitude);
                addMyMarkersToMap(latLng);

                // following mode
                CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng)
                        .zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
                CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
                aMap.moveCamera(update);
            }
        }
    }

    //点击Marker的监听响应
    @Override
    public boolean onMarkerClick(Marker marker) {
        Log.e("你点击的是", marker.getTitle());
        return false;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindow = null;
        if (marker.equals(myMarker)) {
            infoWindow = getLayoutInflater().inflate(R.layout.mylocation_custom_info_window, null);
        } else if (marker.equals(myPoiMarker)) {
            infoWindow = getLayoutInflater().inflate(R.layout.mypoi_location_custom_info_window, null);
        } else if (marker.equals(friendMarker)) {
            infoWindow = getLayoutInflater().inflate(R.layout.friendlocation_custom_info_window, null);
        } else if (marker.equals(friendPoiMarker)) {
            infoWindow = getLayoutInflater().inflate(R.layout.friendpoi_location_custom_info_window, null);
        }

        render(marker, infoWindow);
        return infoWindow;
    }

    /**
     * 监听自定义infowindow窗口的infocontents事件回调
     */
    @Override
    public View getInfoContents(Marker marker) {
        View infoContent = null;
        if (marker.equals(myMarker)) {
            infoContent = getLayoutInflater().inflate(R.layout.mylocation_custom_info_contents, null);
        } else if (marker.equals(myPoiMarker)) {
            infoContent = getLayoutInflater().inflate(R.layout.mypoi_location_custom_info_contents, null);
        } else if (marker.equals(friendMarker)) {
            infoContent = getLayoutInflater().inflate(R.layout.friendlocation_custom_info_contents, null);
        } else if (marker.equals(friendPoiMarker)) {
            infoContent = getLayoutInflater().inflate(R.layout.friendpoi_location_custom_info_contents, null);
        }
        render(marker, infoContent);
        return infoContent;
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 监听点击infowindow窗口事件回调
     */
    @Override
    public void onInfoWindowClick(Marker marker) {
        Toast.makeText(this, "你点击了infoWindow窗口" + marker.getTitle(), Toast.LENGTH_SHORT);
    }

    /**
     * 监听amap地图加载成功事件回调
     */
    @Override
    public void onMapLoaded() {
        //设置Marker显示在当前区域，移动相机
        // 设置所有maker显示在当前可视区域地图中
//        LatLngBounds bounds = new LatLngBounds.Builder()
//                .include(DEFAULT_LATLNG)
//                .include(latlng).build();
//        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 150));
    }

    /**
     * 监听开始拖动marker事件回调
     */
    @Override
    public void onMarkerDragStart(Marker marker) {
        Toast.makeText(this, "开始拖动", Toast.LENGTH_SHORT);
    }

    /**
     * 监听拖动marker时事件回调
     */
    @Override
    public void onMarkerDrag(Marker marker) {
        String curDes = marker.getTitle() + "拖动时当前位置:(lat,lng)\n("
                + marker.getPosition().latitude + ","
                + marker.getPosition().longitude + ")";
        Toast.makeText(this, curDes, Toast.LENGTH_SHORT);
    }

    /**
     * 监听拖动marker结束事件回调
     */
    @Override
    public void onMarkerDragEnd(Marker marker) {
        Toast.makeText(this, "停止拖动", Toast.LENGTH_SHORT);
    }

    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
        if (marker.equals(myMarker)) {
            LinearLayout layout_mylocation = (LinearLayout) view.findViewById(R.id.layout_mylocation);
            LinearLayout layout_mylocation_share = (LinearLayout) view.findViewById(R.id.layout_mylocation_share);
            layout_mylocation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    doShareOneTimeLocation();
                    String msg = "发送了当前位置";
                    if (!TextUtils.isEmpty(msg))
                        sendTextMessage(msg);
                }
            });
            layout_mylocation_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sharringLocationLayout.setVisibility(View.VISIBLE);
                    doShareRealTimeLocation();
                    String msg = "正在实时共享";
                    if (!TextUtils.isEmpty(msg))
                        sendTextMessage(msg);
                }
            });
        } else if (marker.equals(myPoiMarker)) {
            LinearLayout layout_mylocation = (LinearLayout) view.findViewById(R.id.layout_mylocation);
            LinearLayout layout_mylocation_share = (LinearLayout) view.findViewById(R.id.layout_mylocation_share);
            layout_mylocation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e("点击去找他", "当前位置");
                }
            });
            layout_mylocation_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e("点击当前位置", "分享位置");
                    doSharePoiLocation();

                }
            });
        } else if (marker.equals(friendMarker)) {
            //朋友位置标记窗口事件
        } else if (marker.equals(friendPoiMarker)) {
            //朋友POI位置标记窗口事件
        }
    }

    @Override
    public void onMapLongClick(LatLng latlng) {
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (realShareIsStop == false) {
                dialog();
            } else {
                finish();
            }
        }
        return false;
    }

    protected void dialog() {
        Builder builder = new Builder(this);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.stop_share_realtime_location_dialog_layout);
        Button stop_realloc_cancel = (Button) window.findViewById(R.id.stop_realloc_cancel);
        Button stop_realloc_ensure = (Button) window.findViewById(R.id.stop_realloc_ensure);
        stop_realloc_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        stop_realloc_ensure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                doStopRealTimeLocation();
                String msg = "结束实时共享";
                if (!TextUtils.isEmpty(msg))
                    sendTextMessage(msg);
                finish();
            }
        });
        alertDialog.show();
    }


    private void doShareRealTimeLocation() {
        shareRelTimeLocationThread = new ShareRelTimeLocationThread();
        realShareIsStop = false;
        shareRelTimeLocationThread.start();
        if (chatType == Constant.CHATTYPE_GROUP) {
            sharringLocationLayout.setVisibility(View.GONE);
            joinSharingWindow.setVisibility(View.VISIBLE);
            sharingMembers.setVisibility(View.VISIBLE);
            friendSharingHint.setVisibility(View.GONE);
            joinBtnLayout.setVisibility(View.GONE);
            listItems.add(AccountUtils.getAccountID());
            if (groupShareAdapter == null) {
                groupShareAdapter = new GroupShareLocMemberAdapter(this, listItems);
                sharingMembers.setAdapter(groupShareAdapter);
            }
            groupShareAdapter.refresh(listItems);
            setHorListWidth();
        }
    }

    private void doStopRealTimeLocation() {
        realShareIsStop = true;
        AMapLocation aloc = aMapLocationClient.getLastKnownLocation();
        ShareLocationRealTimeStop shareLocationRealTimeStop = new ShareLocationRealTimeStop();
        FriendActionsRequest friendActionsRequest = new FriendActionsRequest();
        Location loc = new Location();
        loc.latitude = String.valueOf(aloc.getLatitude());
        loc.longitude = String.valueOf(aloc.getLongitude());
        loc.time = String.valueOf(System.currentTimeMillis());
        loc.province = aloc.getProvince();
        loc.city = aloc.getCity();
        shareLocationRealTimeStop.mLocation = loc;

        SenderInfo senderInfo = new SenderInfo();
        senderInfo.mImid = AccountUtils.getAccountID();
        if (chatType == Constant.CHATTYPE_GROUP) {
            String targetId = PersistUtils.getServiceGroupId(toChatUsername);
            senderInfo.mTargetid = targetId;
            friendActionsRequest.mTargetId = targetId;
            friendActionsRequest.mTargetType = Constant.SHARE_LOC_TYPE_GROUPS;
        } else if (chatType == Constant.CHATTYPE_SINGLE) {
            senderInfo.mTargetid = toChatUsername;
            friendActionsRequest.mTargetId = toChatUsername;
            friendActionsRequest.mTargetType = Constant.SHARE_LOC_TYPE_USERS;
        }
        shareLocationRealTimeStop.mSenderInfo = senderInfo;
        friendActionsRequest.mAccountId = AccountUtils.getAccountID();
        friendActionsRequest.mActionType = Constant.SHARE_LOC_ACTION_STOP_REAL_TIME;
        friendActionsRequest.mActionBody = shareLocationRealTimeStop;

        RestClient.getRestNormalService().actions(friendActionsRequest, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                Log.d("ShareLocation", "stop real Time Successful");

            }

            @Override
            public void failure(RetrofitError error) {
                Log.d("ShareLocation", "real stop Time failed");

            }
        });
        if (groupShareAdapter != null) {
            listItems.remove(AccountUtils.getAccountID());
            groupShareAdapter.refresh(listItems);
            setHorListWidth();
        }
    }

    private void doShareOneTimeLocation() {
        AMapLocation aloc = aMapLocationClient.getLastKnownLocation();
        ShareLocationOneTime shareLocationOneTime = new ShareLocationOneTime();
        FriendActionsRequest friendActionsRequest = new FriendActionsRequest();
        Location loc = new Location();
        loc.latitude = (String.valueOf(aloc.getLatitude()));
        loc.longitude = String.valueOf(aloc.getLongitude());
        loc.time = (String.valueOf(System.currentTimeMillis()));
        loc.province = aloc.getProvince();
        loc.city = aloc.getCity();
        shareLocationOneTime.mLocation = loc;
        SenderInfo senderInfo = new SenderInfo();
        senderInfo.mImid = AccountUtils.getAccountID();
        if (chatType == Constant.CHATTYPE_GROUP) {
            String targetId = PersistUtils.getServiceGroupId(toChatUsername);
            senderInfo.mTargetid = targetId;
            friendActionsRequest.mTargetId = targetId;
            friendActionsRequest.mTargetType = Constant.SHARE_LOC_TYPE_GROUPS;
        } else if (chatType == Constant.CHATTYPE_SINGLE) {
            senderInfo.mTargetid = toChatUsername;
            friendActionsRequest.mTargetId = toChatUsername;
            friendActionsRequest.mTargetType = Constant.SHARE_LOC_TYPE_USERS;
        }
        friendActionsRequest.mAccountId = AccountUtils.getAccountID();
        friendActionsRequest.mActionType = Constant.SHARE_LOC_ACTION_ONE_SHOT;
        shareLocationOneTime.mSenderInfo = senderInfo;
        friendActionsRequest.mActionBody = shareLocationOneTime;

        RestClient.getRestNormalService().actions(friendActionsRequest, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                Log.d("ShareLocation", "One Time Successful");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.d("ShareLocation", "One Time failed");

            }
        });
    }

    public void onStop() {
        super.onStop();
        GlobalContext.getLocationClient().unRegisterLocationListener(this);
        // unregister this event listener when this activity enters the
        // background
        EMChatManager.getInstance().unregisterEventListener(this);
    }


    // Easecom implement listener

    @Override
    public void onEvent(EMNotifierEvent event) {
        EMMessage message = (EMMessage) event.getData();
        switch (event.getEvent()) {
            case EventNewMessage:
                // 获取到message
                String username = null;
                // 群组消息
                if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                    username = message.getTo();
                } else {
                    // 单聊消息
                    username = message.getFrom();
                }
                // 如果是当前会话的消息，刷新聊天页面
                if (username.equals(toChatUsername)) {
                    message_list.refreshSelectLast();
                    // 声音和震动提示有新消息
                    //EaseUI.getInstance().getNotifier().viberateAndPlayTone(message);
                    // TODO: 2016/2/1
                } else {
                    // 如果消息不是和当前聊天ID的消息
//                    EaseUI.getInstance().getNotifier().onNewMsg(message);
                }
                break;
            case EventDeliveryAck:
            case EventReadAck:
                // 获取到message
                message_list.refresh();
                break;
            case EventOfflineMessage:
                // a list of offline messages
                // List<EMMessage> offlineMessages = (List<EMMessage>)
                // event.getData();
                message_list.refresh();
                break;

            case EventNewCMDMessage: {
//                EMLog.d("ChatActivity透传消息", "收到透传消息");
//                //获取消息body
//                CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
//                final String action = cmdMsgBody.action;//获取自定义action
//                // 群组消息
//                if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
//                    username = message.getTo();
//                } else {
//                    // 单聊消息
//                    username = message.getFrom();
//                }
//                Log.e("透传action", action);
//                switch (action) {
//                    case Constant.SHARE_LOC_ACTION_ONE_SHOT: {
//                        Log.d("发送一次位置", "one");
//                        // 如果是当前会话的消息，地图上添加标记点
//                        if (username.equals(toChatUsername)) {
//                          HashMap<String ,String> params = cmdMsgBody.params;
//                            for(Map.Entry<String, String> entry : params.entrySet()){
//                                System.out.println("遍历"+entry.getKey()+"="+entry.getValue());
//                            }
//
//                        } else {
//                            // 如果消息不是和当前聊天ID的消息
////                    EaseUI.getInstance().getNotifier().onNewMsg(message);
//                        }
//
//                        break;
//                    }
//                    default:
//                        break;
//                }
                break;
            }
            default:
                break;
        }

    }

    //发送消息方法
    //==========================================================================
    private void sendTextMessage(String content) {

        if (!isSita) {
            EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
            sendMessage(message);
        } else {
            EMMessage message = createSentTextMsg(toChatUsername, content);
            sendSitaMessage(message);

        }

    }


    //创建一条发送TextMsg
    private EMMessage createSentTextMsg(String to, String content) {
        EMMessage msg = EMMessage.createSendMessage(EMMessage.Type.TXT);
        TextMessageBody body = new TextMessageBody(content);
        msg.addBody(body);
        msg.setTo(to);
        msg.setFrom(AccountUtils.getAccountID());
        msg.setMsgTime(System.currentTimeMillis());
        return msg;
    }


    private void sendMessage(EMMessage message) {
//        if(chatFragmentListener != null){
//            //设置扩展属性
//            chatFragmentListener.onSetMessageAttributes(message);
//        }
        // 如果是群聊，设置chattype,默认是单聊
        if (chatType == Constant.CHATTYPE_GROUP) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        } else if (chatType == Constant.CHATTYPE_CHATROOM) {
            message.setChatType(EMMessage.ChatType.ChatRoom);
        }
        //发送消息
        EMChatManager.getInstance().sendMessage(message, null);
        //刷新ui
        message_list.refreshSelectLast();
    }

    private void sendSitaMessage(final EMMessage message) {

//        accountId: 用户在系统中唯一编号
//        TargetType 可以为以下任一值(全部大写或者全部小写):
//              USERS("users"), GROUPS("groups");
//        targetId: 可以是一个，也可以是多个，用","分开
//        message: 文本消息内容

        TypedString accountId = new TypedString(AccountUtils.getAccountID());
        TypedString targetType = new TypedString("users");
        TypedString targetId = new TypedString(message.getTo());
        String body = ((TextMessageBody) message.getBody()).getMessage();
        TypedString msg = new TypedString(body);

        RestClient.getRestService().sendMessage(accountId, targetType, targetId, msg, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                Log.d("Chat", "Single send ok");
                if (isSita) {
                    EMChatManager.getInstance().importMessage(message, true);
                    message_list.refreshSelectLast();
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Log.d("Chat", "Single send failed");
                // TODO: 2016/2/2 if send failed, need mark the message and add it into conversation 
            }
        });


    }


    // Share Location
    // ================================================================================================

    private void doSharePoiLocation() {

        AMapLocation aloc = aMapLocationClient.getLastKnownLocation();
        ShareLocationPOI shareLocationPOI = new ShareLocationPOI();
        FriendActionsRequest friendActionsRequest = new FriendActionsRequest();

        Location loc = new Location();
        loc.latitude = (String.valueOf(aloc.getLatitude()));
        loc.longitude = String.valueOf(aloc.getLongitude());
        loc.time = (String.valueOf(System.currentTimeMillis()));
        loc.province = aloc.getProvince();
        loc.city = aloc.getCity();

        shareLocationPOI.mLocation = loc;
        SenderPoiInfo senderPoiInfo = new SenderPoiInfo();
        senderPoiInfo.mImid = AccountUtils.getAccountID();
        if (chatType == Constant.CHATTYPE_GROUP) {
            String targetId = PersistUtils.getServiceGroupId(toChatUsername);
            senderPoiInfo.mTargetid = targetId;
            friendActionsRequest.mTargetId = targetId;
            friendActionsRequest.mTargetType = Constant.SHARE_LOC_TYPE_GROUPS;
        } else if (chatType == Constant.CHATTYPE_SINGLE) {
            senderPoiInfo.mTargetid = toChatUsername;
            friendActionsRequest.mTargetId = toChatUsername;
            friendActionsRequest.mTargetType = Constant.SHARE_LOC_TYPE_USERS;
        }
        shareLocationPOI.mSenderInfo = senderPoiInfo;
        friendActionsRequest.mAccountId = AccountUtils.getAccountID();
        friendActionsRequest.mActionType = Constant.SHARE_LOC_ACTION_POI;
        friendActionsRequest.mActionBody = shareLocationPOI;

        RestClient.getRestNormalService().actions(friendActionsRequest, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                Log.d("ShareLocation", "poi Successful");

            }

            @Override
            public void failure(RetrofitError error) {
                Log.d("ShareLocation", "poi failed");
            }
        });


    }


    // MessageList View init

    /**
     * 设置属性，监听等
     */
    protected void setUpChatView() {
//        titleBar.setTitle(toChatUsername);
        if (chatType == Constant.CHATTYPE_SINGLE) { // 单聊
            // 设置标题
            //// TODO: 2016/2/1

        } else {
            // // TODO: 2016/2/1

        }

        if (chatType != Constant.CHATTYPE_CHATROOM) {
            onConversationInit();
            onMessageListInit();
        }

        // 设置标题栏点击事件
        // TODO: 2016/2/1  

        setRefreshLayoutListener();

        // show forward message if the message is not null
        // TODO: 2016/2/1  

    }


    protected void onConversationInit() {
        // 获取当前conversation对象
        conversation = EMChatManager.getInstance().getConversation(toChatUsername);
        // 把此会话的未读数置为0
        conversation.markAllMessagesAsRead();
        EventBus.getDefault().post(new ConversationMessageHasReadEvent("Conversation Item clicked"));
        // 初始化db时，每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded
        // 这个数目如果比用户期望进入会话界面时显示的个数不一样，就多加载一些
        final List<EMMessage> msgs = conversation.getAllMessages();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            if (chatType == Constant.CHATTYPE_SINGLE) {
                conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
            } else {
                conversation.loadMoreGroupMsgFromDB(msgId, pagesize - msgCount);
            }
        }
    }

    protected void onMessageListInit() {
        message_list.init(toChatUsername, chatType, null);
        //设置list item里的控件的点击事件
        setListItemClickListener();

        message_list.getListView().setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // // TODO: 2016/2/1
                return false;
            }
        });

        isMessageListInited = true;
    }

    protected void setListItemClickListener() {
        message_list.setItemClickListener(new EaseChatMessageList.MessageListItemClickListener() {

            @Override
            public void onUserAvatarClick(String username) {
            }

            @Override
            public void onResendClick(final EMMessage message) {
            }

            @Override
            public void onBubbleLongClick(EMMessage message) {
            }

            @Override
            public boolean onBubbleClick(EMMessage message) {
                return false;
            }
        });
    }

    protected void setRefreshLayoutListener() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (listView.getFirstVisiblePosition() == 0 && !isloading && haveMoreData) {
                            List<EMMessage> messages;
                            try {
                                if (chatType == Constant.CHATTYPE_SINGLE) {
                                    messages = conversation.loadMoreMsgFromDB(message_list.getItem(0).getMsgId(),
                                            pagesize);
                                } else {
                                    messages = conversation.loadMoreGroupMsgFromDB(message_list.getItem(0).getMsgId(),
                                            pagesize);
                                }
                            } catch (Exception e1) {
                                swipeRefreshLayout.setRefreshing(false);
                                return;
                            }
                            if (messages.size() > 0) {
                                message_list.refreshSeekTo(messages.size() - 1);
                                if (messages.size() != pagesize) {
                                    haveMoreData = false;
                                }
                            } else {
                                haveMoreData = false;
                            }

                            isloading = false;

                        } else {
                            Toast.makeText(ChatActivity.this, getResources().getString(R.string.no_more_messages),
                                    Toast.LENGTH_SHORT).show();
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 600);
            }
        });
    }

    /**
     * 点击进入群组详情
     */
    protected void toGroupDetails() {
        if (chatType == Constant.CHATTYPE_GROUP) {
            EMGroup group = EMGroupManager.getInstance().getGroup(toChatUsername);
            if (group == null) {
                Toast.makeText(this, R.string.gorup_not_found, Toast.LENGTH_SHORT).show();
                return;
            }
            startActivityForResult(
                    (new Intent(this, FriendGroupDetailsActivity.class).putExtra("groupId", toChatUsername)),
                    13);
        }
    }

    //--------------------导航监听回调事件-----------------------------
    @Override
    public void onInitNaviFailure() {

    }

    @Override
    public void onInitNaviSuccess() {

    }

    @Override
    public void onStartNavi(int i) {

    }

    @Override
    public void onTrafficStatusUpdate() {

    }

    private static boolean isValidGps(Double longitude, Double latitude) {
        if (longitude == null || latitude == null) {
            return false;
        }
        boolean isZeroLng = Double.compare(longitude, 0) == 0;
        boolean isZeroLat = Double.compare(latitude, 0) == 0;
        return !isZeroLng && !isZeroLat;
    }

    @Override
    public void onLocationChange(AMapNaviLocation aMapNaviLocation) {

    }

    @Override
    public void onGetNavigationText(int i, String s) {

    }

    @Override
    public void onEndEmulatorNavi() {

    }

    @Override
    public void onArriveDestination() {

    }

    @Override
    public void onCalculateRouteSuccess() {
        AMapNaviPath naviPath = aMapNavi.getNaviPath();
        if (naviPath == null) {
            return;
        }
        // 获取路径规划线路，显示到地图上
        mRouteOverLay.setAMapNaviPath(naviPath);
        final String myAvatarUrl = AccountUtils.getAvatar();
        Bitmap myAvatar = AccountUtils.getUserAvatar(myAvatarUrl);
//        mRouteOverLay.setStartPointBitmap(redpin_zoom);
//        mRouteOverLay.setEndPointBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.location_end));
        mRouteOverLay.addToMap();

        LatLng startLatLng = new LatLng(mNaviStart.getLatitude(), mNaviStart.getLongitude());
        LatLng endLatLng = new LatLng(mNaviEnd.getLatitude(), mNaviEnd.getLongitude());
        LatLngBounds bounds = new LatLngBounds.Builder()
                .include(startLatLng).include(endLatLng).build();
        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 150));


    }

    @Override
    public void onCalculateRouteFailure(int i) {
        Toast.makeText(this, "路径规划出错", Toast.LENGTH_SHORT);
    }

    @Override
    public void onReCalculateRouteForYaw() {

    }

    @Override
    public void onReCalculateRouteForTrafficJam() {

    }

    @Override
    public void onArrivedWayPoint(int i) {

    }

    @Override
    public void onGpsOpenStatus(boolean b) {

    }

    @Override
    public void onNaviInfoUpdated(AMapNaviInfo aMapNaviInfo) {

    }

    @Override
    public void onNaviInfoUpdate(NaviInfo naviInfo) {

    }

    @Override
    public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {

    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {

    }

    @Override
    public void hideCross() {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {

    }

    @Override
    public void hideLaneInfo() {

    }

    @Override
    public void onCalculateMultipleRoutesSuccess(int[] ints) {

    }

    @Override
    public void notifyParallelRoad(int i) {

    }


    //

    public class ShareRelTimeLocationThread extends Thread {
        private AMapLocationClient lc;

        public ShareRelTimeLocationThread() {
            this.lc = GlobalContext.getLocationClient();
        }

        @Override
        public void run() {
            while (!realShareIsStop) {
                AMapLocation aloc = lc.getLastKnownLocation();
                ShareLocationRealTime shareLocationRealTime = new ShareLocationRealTime();
                FriendActionsRequest friendActionsRequest = new FriendActionsRequest();

                Location loc = new Location();
                loc.latitude = (String.valueOf(aloc.getLatitude()));
                loc.longitude = String.valueOf(aloc.getLongitude());
                loc.time = (String.valueOf(System.currentTimeMillis()));
                loc.province = aloc.getProvince();
                loc.city = aloc.getCity();

                shareLocationRealTime.mLocation = loc;

                SenderInfo senderInfo = new SenderInfo();
                senderInfo.mImid = AccountUtils.getAccountID();
                if (chatType == Constant.CHATTYPE_GROUP) {
                    String targetId = PersistUtils.getServiceGroupId(toChatUsername);
                    senderInfo.mTargetid = targetId;
                    friendActionsRequest.mTargetId = targetId;
                    friendActionsRequest.mTargetType = Constant.SHARE_LOC_TYPE_GROUPS;
                } else if (chatType == Constant.CHATTYPE_SINGLE) {
                    senderInfo.mTargetid = toChatUsername;
                    friendActionsRequest.mTargetId = toChatUsername;
                    friendActionsRequest.mTargetType = Constant.SHARE_LOC_TYPE_USERS;
                }
                shareLocationRealTime.mSenderInfo = senderInfo;
                friendActionsRequest.mAccountId = AccountUtils.getAccountID();
                friendActionsRequest.mActionType = Constant.SHARE_LOC_ACTION_REAL_TIME;
                friendActionsRequest.mActionBody = shareLocationRealTime;

                RestClient.getRestNormalService().actions(friendActionsRequest, new Callback<RestResponse>() {
                    @Override
                    public void success(RestResponse restResponse, Response response) {
                        Log.d("ShareLocation", "real Time Successful");

                    }

                    @Override
                    public void failure(RetrofitError error) {
                        Log.d("ShareLocation", "real Time failed");

                    }
                });
                try {
                    this.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public void setHorListWidth() {
        ListAdapter listAdapter = sharingMembers.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalWidth = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, sharingMembers);
            listItem.measure(0, 0);
            totalWidth += listItem.getMeasuredWidth();
        }

        ViewGroup.LayoutParams params = sharingMembers.getLayoutParams();
        params.width = totalWidth;
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        sharingMembers.setLayoutParams(params);
    }

    //计算驾车路线
    private void calculateDriveRoute(EMMessage mEMMessage) {
        //当前位置为开始位置
        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        mNaviStart.setLatitude(location.getLatitude());
        mNaviStart.setLongitude(location.getLongitude());
        //搜索位置为结束位置
        try {
            mNaviEnd.setLatitude(Double.parseDouble(mEMMessage.getStringAttribute("poiLatitude")));
            mNaviEnd.setLongitude(Double.parseDouble(mEMMessage.getStringAttribute("poiLongitude")));
        } catch (EaseMobException e) {
            e.printStackTrace();
        }
        mStartPoints.clear();
        mEndPoints.clear();
        mStartPoints.add(mNaviStart);
        mEndPoints.add(mNaviEnd);
        boolean isSuccess = aMapNavi.calculateDriveRoute(mStartPoints,
                mEndPoints, null, PathPlanningStrategy.DRIVING_DEFAULT);
        if (!isSuccess) {
            Toast.makeText(this, "路线计算失败,检查参数情况", Toast.LENGTH_SHORT);
        }

    }

}
